<template>
   <!-- 弹窗组件 -->
   <div class="dialog-box">
      <el-dialog
         v-model="dialogVisible"
         title="关联产品"
         width="1000"
      >
         <div class="dialog-content">
            <!-- 分组区域保持不变 -->
            <!-- <div class="row-1">
               <div
                  class="row-1-title"
                  v-show="!is_search"
               >
                  <div>产品分组</div>
                  <div
                     style="cursor: pointer"
                     @click="handleSearch"
                  >
                     <el-icon><Search /></el-icon>
                  </div>
               </div>
               <div
                  class="row-1-title"
                  v-show="is_search"
               >
                  <el-input
                     style="width: 100%"
                     v-model="textValue"
                     placeholder="请输入"
                     placeholder-class="input-placeholder"
                     ref="SerRef"
                  />
               </div>
               <div
                  class="row-1-content"
                  @click="handleGroupClick(item)"
                  v-for="item in FilterList"
                  :style="{ background: item.id == filterParams.group_id ? '#172B4D' : 'transparent', color: item.id == filterParams.group_id ? '#fff' : '#172B4D' }"
                  :key="item.id"
               >
                  <div>{{ item.name }}</div>
               </div>
            </div> -->

            <!-- 左侧产品列表 -->
            <div class="row-2">
               <div class="row-2-search">
                  <el-input
                     placeholder="请输入关键字"
                     suffix-icon="Search"
                     v-model="filterParams.keywords"
                     @input="handleInput"
                  />
               </div>
               <div class="table-container">
                  <el-table
                     ref="leftTableRef"
                     :data="tableData"
                     style="width: 100%"
                     border
                     @selection-change="handleSelectionChange"
                     :row-key="(row:User) => row.id"
                  >
                     <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                     />
                     <el-table-column
                        label="产品名称"
                        width="100"
                        align="center"
                     >
                        <template #default="scope">{{ scope.row.name }}</template>
                     </el-table-column>
                     <el-table-column
                        prop="no"
                        label="产品编码"
                        width="120"
                        align="center"
                     />
                     <el-table-column
                        prop="spu_measure_unit_id"
                        label="采购单位"
                        show-overflow-tooltip
                        width="120"
                        align="center"
                     />
                     <el-table-column
                        prop="open_unit_name"
                        label="拆零"
                        show-overflow-tooltip
                        width="120"
                        align="center"
                     />
                  </el-table>
               </div>
            </div>

            <!-- 右侧已选产品列表 -->
            <div class="row-3">
               <div class="row-head">
                  <div class="row-head-left">已选{{ rightCount }}项</div>
                  <div
                     class="row-head-right"
                     @click="clearAll"
                     v-if="rightCount > 0"
                  >
                     清空
                  </div>
               </div>
               <div class="table-container">
                  <el-table
                     :data="rightTableData"
                     style="width: 100%"
                     border
                  >
                     <el-table-column
                        prop="name"
                        label="产品名称"
                        width="100"
                        align="center"
                     />
                     <el-table-column
                        prop="no"
                        label="产品编码"
                        width="100"
                        align="center"
                     />
                     <el-table-column
                        prop="measure_unit_name"
                        label="采购单位"
                        width="100"
                        align="center"
                     />
                     <el-table-column
                        prop="specification"
                        label="拆零"
                        width="100"
                        align="center"
                     />
                     <el-table-column
                        label="操作"
                        width="100"
                        align="center"
                     >
                        <template #default="scope">
                           <el-button
                              type="danger"
                              link
                              @click="removeRow(scope.row)"
                              >移除</el-button
                           >
                        </template>
                     </el-table-column>
                  </el-table>
               </div>
            </div>
         </div>

         <template #footer>
            <div class="dialog-footer">
               <el-button @click="dialogVisible = false">取消</el-button>
               <el-button
                  color="#626aef"
                  @click="submit"
                  >确认</el-button
               >
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup lang="ts">
   import { ref, computed, nextTick, defineProps } from "vue";
   import { Search } from "@element-plus/icons-vue";
   import type { ElTable } from "element-plus";
   import api from "@/api/index.js";
   import { productDataType } from "../suppliersType";
   const filterParams = ref<{ keywords: string; group_id: number | null }>({
      keywords: "",
      group_id: null,
   });
   const fatherPrductData = ref<productDataType[]>([]); // 父组件传递过来的数据
   interface User {
      date: string;
      name: string;
      address: string;
      id: number;
   }
   interface Product {
      id: number;
      name: string;
      no: string;
      specification: string;
      img: string[];
   }
   const tableData = ref<Product[]>([]);
   // 左侧表格数据
   const getTableData = async () => {
      const res = await api.publicFun.getProductList(filterParams.value);
      if (res.code == 200) {
         tableData.value = res.data;
      }
   };
   const props = defineProps<{
      productData: productDataType[];
   }>();

   // 使用唯一标识id作为选中项的key
   const selectedKeys = ref<Set<number>>(new Set());
   const leftTableRef = ref<InstanceType<typeof ElTable>>();

   // 右侧表格数据：从tableData中过滤出选中的项
   const rightTableData = computed(() => tableData.value.filter((item) => selectedKeys.value.has(item.id)));

   const rightCount = computed(() => selectedKeys.value.size);

   // 处理左侧表格选中变化
   function handleSelectionChange(selection: User[]) {
      is_search.value = false; //隐藏搜索框
      selectedKeys.value = new Set(selection.map((item) => item.id));
   }

   // 更新左侧表格选中状态
   function updateLeftTableSelection() {
      nextTick(() => {
         const table = leftTableRef.value;
         if (!table) return;

         // 找到要取消选中的行
         tableData.value.forEach((row) => {
            if (selectedKeys.value.has(row.id)) {
               table.toggleRowSelection(row, true);
            } else {
               table.toggleRowSelection(row, false);
            }
         });
      });
   }

   // 移除单行
   function removeRow(row: User) {
      selectedKeys.value.delete(row.id);
      selectedKeys.value = new Set(selectedKeys.value); // 触发响应式更新
      nextTick(() => {
         const table = leftTableRef.value;
         if (!table) return;
         table.toggleRowSelection(row, false);
      });
   }

   // 清空所有
   function clearAll() {
      selectedKeys.value.clear();
      selectedKeys.value = new Set(); // 触发响应式更新
      nextTick(() => {
         const table = leftTableRef.value;
         if (!table) return;
         table.clearSelection();
      });
   }
   // 产品分组列表
   const productGroupList = ref<
      {
         id: number;
         name: string;
      }[]
   >([]);
   // 获取产品分组列表
   const getProductGroupList = async () => {
      const res = await api.publicFun.getProductGroupList();
      if (res.code == 200) {
         productGroupList.value = res.data;
      }
   };

   // 打开弹窗
   const dialogVisible = ref(false);
   const openLoading = async () => {
      fatherPrductData.value = props.productData;
      filterParams.value = {} as unknown as { keywords: string; group_id: number | null };
      dialogVisible.value = true;
      await getProductGroupList();
      await getTableData();

      // 检查父组件数据和表格数据的匹配，并自动勾选
      if (fatherPrductData.value && fatherPrductData.value.length > 0) {
         const matchingIds = new Set(fatherPrductData.value.map((item) => item.id));
         selectedKeys.value = matchingIds;
         nextTick(() => {
            const table = leftTableRef.value;
            if (!table) return;

            tableData.value.forEach((row) => {
               if (matchingIds.has(row.id)) {
                  table.toggleRowSelection(row, true);
               }
            });
         });
      }
   };
   const emit = defineEmits(["SelectRelatedProducts"]);

   const submit = () => {
      // TODO: 处理表单提交
      dialogVisible.value = false;
      if (rightTableData.value.length > 0) {
         emit("SelectRelatedProducts", rightTableData.value);
      }
   };
   import { ElInput } from "element-plus";
   import { watch } from "vue";
   import { isArray } from "lodash";
   const textValue = ref<string>(""); //搜索值
   const is_search = ref<boolean>(false); //是否点击搜索框
   const SerRef = ref<InstanceType<typeof ElInput>>();
   const handleSearch = () => {
      is_search.value = !is_search.value;
   };
   // 监听is_search变化，当为true时自动获取焦点
   watch(is_search, (newVal) => {
      if (newVal) {
         nextTick(() => {
            SerRef.value?.focus();
         });
      }
   });
   const FilterList = computed(() => {
      if (textValue.value) {
         return productGroupList.value.filter((item) => item.name.includes(textValue.value));
      } else {
         return productGroupList.value;
      }
   });
   const handleGroupClick = async (item: { id: number; name: string }) => {
      filterParams.value.group_id = item.id;
      await getTableData();
   };
   const handleInput = () => {
      getTableData();
   };
   defineExpose({ openLoading });
</script>

<style lang="scss" scoped>
   .dialog-content {
      display: flex;
      height: 400px;
      flex-direction: row;
      gap: 10px;
      .row-1 {
         flex: 0.7;
         border: 1px solid #f0f0f0;
         .row-1-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;
            width: 76%;
            height: 28px;
            border-bottom: 1px solid #f0f0f0;
            margin: 0 auto;
            color: #172b4d;
         }
         .row-1-content {
            padding: 10px;
            border-radius: 4px;
            margin: 0 10px;
            &:hover {
               background: #edecff;
               cursor: pointer;
               color: #626aef;
            }
         }
      }
      .row-2 {
         flex: 1;
         border: 1px solid #f0f0f0;
         display: flex;
         flex-direction: column;
         overflow: hidden;

         .row-2-search {
            padding: 10px;
            width: 50%;
         }

         .table-container {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;

            &::-webkit-scrollbar {
               width: 6px;
               height: 6px;
            }

            &::-webkit-scrollbar-thumb {
               border-radius: 3px;
               background: #ddd;
            }

            &::-webkit-scrollbar-track {
               border-radius: 3px;
               background: #f5f5f5;
            }

            .el-table {
               height: 100%;
            }
         }
      }
      .row-3 {
         flex: 1;
         border: 1px solid #f0f0f0;
         .row-head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;
            .row-head-left {
            }
            .row-head-right {
               color: #766fff;
               cursor: pointer;
            }
         }
      }
   }
   ::v-deep .el-dialog {
      --el-dialog-padding-primary: 0px;
   }
   ::v-deep .el-dialog__header {
      padding: 10px 16px;
      border-bottom: 1px solid #f0f0f0;
      font-weight: bold;
   }
   ::v-deep .dialog-footer {
      padding: 10px 16px;
      border-top: 1px solid #f0f0f0;
   }
   ::v-deep .el-dialog__headerbtn .el-dialog__close {
      color: #000;
   }
   ::v-deep .el-dialog__body {
      padding: 20px 10px;
   }
   :deep(.cell) {
      white-space: nowrap;
      text-overflow: ellipsis;
   }
   :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
      background-color: #6860ff;
      border-color: #6860ff;
   }
   :deep(.el-checkbox__inner:hover) {
      border-color: #626aef !important;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      background-color: #6860ff;
   }
   :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
      border-color: #6860ff;
   }
</style>
